package org.xiyinjihe.platform.filter;

import org.xiyinjihe.platform.dto.resp.BaseRespDTO;
import org.xiyinjihe.platform.dto.resp.ExceptionDTO;
import org.xiyinjihe.platform.enums.ResponseStatus;
import org.xiyinjihe.platform.error.CommonError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.xiyinjihe.platform.exception.CommonException;

/**
 * Created by sunwen on 2018/11/14.
 * (๑•̀ㅂ•́)و✧
 */
@ControllerAdvice
public class MyControllerAdvice {

    private static final Logger logger = LoggerFactory.getLogger(MyControllerAdvice.class);

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseRespDTO jsonErrorHandler(Exception ex){
        BaseRespDTO dto = new ExceptionDTO();
        dto.setStatus(ResponseStatus.FAIL);
        if(ex instanceof CommonException){
            CommonException ce = (CommonException) ex;
            dto.setErrorCode(ce.getErrorCode());
            dto.setErrorTitle(ce.getErrorTitle());
            dto.setErrorMsg(ce.getErrorMsg());
        }else {
            dto.setErrorCode(CommonError.SYSTEM_ERROR.getErrorCode());
            if (ex.getMessage() != null && ex.getMessage().length() > 0) {
                dto.setErrorTitle(CommonError.SYSTEM_ERROR.getErrorTitle() + ":" + ex.getMessage());
                dto.setErrorMsg(CommonError.SYSTEM_ERROR.getErrorTitle() + ":" + ex.getMessage());
            } else {
                dto.setErrorTitle(CommonError.SYSTEM_ERROR.getErrorTitle());
                dto.setErrorMsg(CommonError.SYSTEM_ERROR.getErrorTitle());
            }
        }
        logger.error("捕获到Exception异常",ex);
        return dto;
    }
}
